package com.a01_2021.thousandstimes.instance.service.impl;

import com.a01_2021.thousandstimes.exception.CustomException;
import com.a01_2021.thousandstimes.exception.CustomExceptionType;
import com.a01_2021.thousandstimes.instance.entity.Note;
import com.a01_2021.thousandstimes.instance.mapper.NoteMapper;
import com.a01_2021.thousandstimes.instance.service.INoteService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author E1xP
 * @since 2021-03-10
 */
@Service
public class NoteServiceImpl extends ServiceImpl<NoteMapper, Note> implements INoteService {

    @Resource
    NoteMapper noteMapper;

    /**
     * 添加便签
     *
     * @param userId      用户id
     * @param noteName    便签名字
     * @param noteContent 便签内容
     * @return Note实体
     */
    @Override
    public Note addNote(long userId, String noteName, String noteContent) {
        Note note = new Note(null, userId, noteName, noteContent, LocalDateTime.now());
        noteMapper.insert(note);
        return note;
    }

    /**
     * 通过用户id获取全部便签
     *
     * @param userId 用户id
     * @return 便签列表
     */
    @Override
    public List<Note> getNotes(long userId) {
        QueryWrapper<Note> noteQueryWrapper = new QueryWrapper<>();
        noteQueryWrapper.eq("user_id", userId);
        return noteMapper.selectList(noteQueryWrapper);
    }

    /**
     * 批量添加便签
     *
     * @param userId   用户id
     * @param noteList 便签列表
     * @return 便签列表
     */
    @Override
    public List<Note> addNotes(long userId, List<Note> noteList) {
        LocalDateTime localDateTime = LocalDateTime.now();
        for (Note item : noteList) {
            item.setUserId(userId);
            item.setNoteDate(localDateTime);
            noteMapper.insert(item);
        }
        return noteList;
    }

    /**
     * 修改便签
     *
     * @param userId 用户id
     * @param note   便签
     * @return Note实体
     * @throws CustomException 当便签不存在，便签不属于该用户时抛出该异常
     */
    @Override
    public Note updateNote(long userId, Note note) throws CustomException {
        Note resultNote = noteMapper.selectById(note);
        if (resultNote == null) {
            throw new CustomException(CustomExceptionType.NOTE_NOT_FOUND_ERROR, "该便签不存在");
        }
        if (resultNote.getUserId() != userId) {
            throw new CustomException(CustomExceptionType.OPERATION_NOT_ALLOW, "不允许修改他人便签");
        }
        resultNote.setNoteContent(note.getNoteContent());
        resultNote.setNoteName(note.getNoteName());
        noteMapper.updateById(resultNote);
        return resultNote;
    }
}
